from django.core.paginator import Paginator
from django.shortcuts import render

# Create your views here.
from rest_framework.response import Response
from rest_framework.views import APIView

from users.Ser import NewsModelSerializer, AdvertModelSerializer
from users.models import News, Advert


class NewsAPI(APIView):
    def get(self, request):
        id = request.GET.get('id')
        pid = request.GET.get('pid')
        if id:
            data = News.objects.all()
            page1 = Paginator(data, 1)
            page2 = page1.page(pid)
            data1 = NewsModelSerializer(page2, many=True)
            return Response({
                'data': data1.data,
                'page_range': [i for i in page1.page_range]
            })
        else:
            data = News.objects.all()
            data = NewsModelSerializer(data, many=True)
            return Response(data.data)

    def post(self, request):
        data1 = NewsModelSerializer(data=request.data)
        if data1.is_valid():
            data1.save()
            return Response({'code': 200})


class AdvertAPI(APIView):
    def get(self, request):
        id = request.GET.get('id')
        pid = request.GET.get('pid')
        if id:
            data = Advert.objects.all()
            page1 = Paginator(data, 1)
            page2 = page1.page(pid)
            data1 = AdvertModelSerializer(page2, many=True)
            return Response({
                'data': data1.data,
                'page_range': [i for i in page1.page_range]
            })
        else:
            data = Advert.objects.all()
            data = AdvertModelSerializer(data, many=True)
            return Response(data.data)

    def post(self, request):
        data1 = AdvertModelSerializer(data=request.data)
        if data1.is_valid():
            data1.save()
            return Response({'code': 200})
